<?php 
namespace app\admin\controller;

use think\Request;
use think\Exception;
use app\common\model\Carousel as CarouselModel;
use app\common\controller\Upload;
use think\Controller;

class Carousel extends Controller
{
	/**
	 * 轮播图列表、添加轮播图
	 * @param Request $request
	 * @return unknown
	 */
	public function index(Request $request)
	{
		if ($request->isAjax()) {
			$data = $request->post('');
			try {
				if (array_key_exists('id',$data)) {
					if (preg_match('/^(data:\s*image\/(\w+);base64,)/',$data['img'],$result)) {
						$data['img'] = Upload::base64($data['img'],config('path.carousel'));
					}
					CarouselModel::get($data['id'])->save($data);
				} else {
					$data['img'] = Upload::base64($data['img'],config('path.carousel'));
					CarouselModel::create($data);
				}
				
			} catch (Exception $e) {
				return $this->error($e->getMessage());
			}
			return $this->success('设置成功');
		}
		$list = CarouselModel::where(['state' => 1])->select()->toArray();
		$this->assign('list',json_encode($list));
		return view();
	}
	
	/**
	 * 删除轮播图
	 * @param Request $request
	 * @return unknown
	 */
	public function delete(Request $request)
	{
		$id = $request->param('id');
		try {
			$carousel = CarouselModel::get($id);
			$carousel->save(['state' =>0]);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('删除成功');
	}
}